package com.zb.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zb.common.po.config.ConfigInfo;

public class CookieUtil {

    private static ConfigInfo configInfo = (ConfigInfo) SpringHelper
            .getBean("configInfo");

    private static String domain = configInfo.getDomain();

    private static int seconds = -1;// 关闭浏览器时cookie即过期

    /**
     * 设置cookie
     * 
     * @param name
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String name,
            String value) {
        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(value))
            return;
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setMaxAge(seconds);
        cookie.setPath("/");
        response.setHeader("P3P",
                "CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
        response.addCookie(cookie);
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        try {
            Cookie cookies[] = request.getCookies();
            if (cookies != null) {
                for (int i = 0; i < cookies.length; i++) {
                    if (name.equalsIgnoreCase(cookies[i].getName())) {
                        return cookies[i].getValue();
                    }
                }
            }
        } catch (Exception e) {
        }
        return "";
    }

    public static void removeCookieValue(HttpServletRequest request,
            HttpServletResponse response, String name) {
        try {
            Cookie cookies[] = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (name.equalsIgnoreCase(cookie.getName())) {
                        cookie = new Cookie(name, null);
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        cookie.setDomain(domain);
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}